package top.goldenyear.porpoise.framework.web.core.model;

import cn.hutool.v7.core.convert.ConvertUtil;
import com.easy.query.core.api.pagination.EasyPageResult;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
import lombok.NoArgsConstructor;
import top.goldenyear.porpoise.framework.web.core.model.query.QPage;

/**
 * @author airhead
 */
@Data
@NoArgsConstructor
public class PageResult<T> {
  private int total;
  private int pageNumber;
  private int pageSize;
  private List<T> records;

  public PageResult(EasyPageResult<T> pageResult, int pageNumber, int pageSize) {
    if (pageResult != null) {
      this.records = pageResult.getData();
      this.total = ConvertUtil.toInt(pageResult.getTotal(), 0);
    }

    this.pageNumber = pageNumber;
    this.pageSize = pageSize;
  }

  public PageResult(EasyPageResult<T> pageResult, QPage qPage) {
    if (pageResult != null) {
      this.records = pageResult.getData();
      this.total = ConvertUtil.toInt(pageResult.getTotal(), 0);
    }

    if (qPage != null) {
      this.pageNumber = qPage.getPageNumber();
      this.pageSize = qPage.getPageSize();
    }
  }

  public PageResult(QPage qPage) {
    this.records = new ArrayList<>();
    this.total = 0;
    if (qPage != null) {
      this.pageNumber = qPage.getPageNumber();
      this.pageSize = qPage.getPageSize();
    }
  }

  public static <T> PageResult<T> empty() {
    PageResult<T> pageResult = new PageResult<>();
    pageResult.setRecords(new ArrayList<>());
    pageResult.setTotal(0);
    pageResult.setPageNumber(QPage.PAGE_NUMBER);
    pageResult.setPageSize(QPage.PAGE_NUMBER);
    return pageResult;
  }

  public static <T> PageResult<T> of(QPage qPage) {
    PageResult<T> pageResult = new PageResult<>();
    pageResult.setRecords(new ArrayList<>());
    pageResult.setTotal(0);
    pageResult.setPageNumber(qPage.getPageNumber());
    pageResult.setPageSize(qPage.getPageSize());
    return pageResult;
  }

  public int getTotalPage() {
    return total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
  }
}
